<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item prop="storageId">
        <el-select v-model="queryParams.storageId" placeholder="请选择前置仓" clearable>
          <el-option v-for="item in storages" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入配送员名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['rider:rider:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['rider:rider:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="riderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="配送员编号" align="center" prop="id" v-if="true"/>
      <el-table-column label="配送员名字" align="center" prop="name" />
      <el-table-column label="联系电话" align="center" prop="phone" />

      <el-table-column
          prop="storageId"
          align="center"
          show-overflow-tooltip
          label="配送仓库">
        <template slot-scope="scope">
          {{ storageMap[scope.row.storageId] }}
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          {{ scope.row.state | stateType }}
        </template>
      </el-table-column>

      <el-table-column label="开工状态" align="center" prop="workState">
        <template slot-scope="scope">
          {{ scope.row.workState | workStateType }}
        </template>
      </el-table-column>


      <el-table-column
          align="center"
          width="160"
          label="配送时间">
        <template slot-scope="scope">
          {{ scope.row.deliveryStart }}  ~ {{ scope.row.deliveryEnd }}
        </template>
      </el-table-column>


      <el-table-column
          align="center"
          width="160"
          label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          width="160"
          label="修改时间">
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>



      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <el-button v-show="scope.row.state === 1" type="primary" size="mini" @click="onDisable(scope.row)">禁用</el-button>
          <el-button v-show="scope.row.state === 0" type="primary" size="mini" @click="onOpen(scope.row)">启用</el-button>
          <el-button v-show="scope.row.state === 1 && scope.row.workState === 1" type="primary" size="mini" @click="onRest(scope.row)">休息</el-button>
          <el-button v-show="scope.row.state === 1 && scope.row.workState === 0" type="primary" size="mini" @click="onWork(scope.row)">开工</el-button>
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['rider:rider:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['rider:rider:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配送对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="配送员名字" prop="name">
          <el-input v-model="form.name" placeholder="请输入配送员名字" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item prop="phone" label="新密码">
          <el-input v-model="form.newPassword" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item prop="name" label="配送周期">
          <el-checkbox-group v-model="form.weekNumberIds" @change="onChanged">
            <el-checkbox label="周一"></el-checkbox>
            <el-checkbox label="周二"></el-checkbox>
            <el-checkbox label="周三"></el-checkbox>
            <el-checkbox label="周四"></el-checkbox>
            <el-checkbox label="周五"></el-checkbox>
            <el-checkbox label="周六"></el-checkbox>
            <el-checkbox label="周日"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item prop="date" label="配送时间">
          <div class="dateList">
            <el-time-select
                v-model="form.deliveryStart"
                :picker-options="{ start: '00:00', step: '00:15', end: '24:00' }"
                placeholder="起始时间">
            </el-time-select>
            <el-time-select
                v-model="form.deliveryEnd"
                :picker-options="{ start: '00:00', step: '00:15', end: '24:00', minTime: form.deliveryStart }"
                placeholder="结束时间">
            </el-time-select>
          </div>
        </el-form-item>
        <el-form-item prop="storageId" label="配送仓库">
          <el-select v-model="form.storageId" placeholder="请选择仓库" clearable filterable>
            <el-option
                v-for="item in storages"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="消息推送订阅">
          <img style="width: 162px;height: 162px;" :src="qrcode" alt="">
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRider, getRider, delRider, addRider, updateRider,
  updateStateToAbort,
  updateBusinessWorkState,
  updateStateToNomral,
  updateBusinessStateToRest,
  getRiderQrcodeImage} from "@/api/rider/rider";
import {getStorageQrcodeImage, listAllStorage} from "@/api/storage/storage";

const num2TextMap = {
  1: '周一',
  2: '周二',
  3: '周三',
  4: '周四',
  5: '周五',
  6: '周六',
  7: '周日'
}
const text2NumMap = {
  '周一': 1,
  '周二': 2,
  '周三': 3,
  '周四': 4,
  '周五': 5,
  '周六': 6,
  '周日': 7
}

export default {
  name: "Rider",
  filters: {
    stateType(val) {
      if (!val) {
        return '禁用'
      } else {
        return '正常'
      }
    },
    workStateType(val) {
      if (!val) {
        return '休息'
      } else {
        return '开工'
      }
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 配送表格数据
      riderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        deliveryStart: undefined,
        deliveryEnd: undefined,
        phone: undefined,
        avatarUrl: undefined,
        lastLoginIp: undefined,
        gmtLastLogin: undefined,
        loginType: undefined,
        openId: undefined,
        state: undefined,
        workState: undefined,
        password: undefined,
        storageId: undefined,
        deliveryRadius: undefined,
        weekNumberIds:[],
        newPassword: undefined,
      },
      storages: [],
      qrcode: '',
      // 仓库map
      storageMap: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "配送员名字不能为空", trigger: "blur" }
        ],
        storageId: [
          { required: true, message: "所属仓库不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.listAllStorage()
    this.getList();
  },
  methods: {
    onChanged() {
    },
    listAllStorage() {
      listAllStorage().then(({ data }) => {
        this.storages = data
        this.storages.forEach(storage => {
          this.storageMap[storage.id] = storage.name
        })
      })
    },
    /** 查询配送列表 */
    getList() {
      this.loading = true;
      listRider(this.queryParams).then(response => {
        this.riderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        deliveryStart: undefined,
        deliveryEnd: undefined,
        phone: undefined,
        avatarUrl: undefined,
        lastLoginIp: undefined,
        gmtLastLogin: undefined,
        loginType: undefined,
        openId: undefined,
        state: undefined,
        workState: undefined,
        createTime: undefined,
        updateTime: undefined,
        password: undefined,
        storageId: undefined,
        deliveryRadius: undefined,
        createBy: undefined,
        newPassword: undefined,
        weekNumberIds:[],
        updateBy: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加配送";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      await getRider(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.weekNumberIds = (this.form.weekNumberIds || []).map(item => num2TextMap[item])
        this.open = true;
        this.title = "修改配送";
      });
      const img= (await getRiderQrcodeImage({riderId: id})).data
      this.qrcode = 'data:image/gif;base64,' + img
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          this.form.weekNumberIds = this.form.weekNumberIds.map(date => (text2NumMap[date]))
          if (this.form.id != null) {
            updateRider(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addRider(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除配送编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delRider(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    async onDisable(rider) {
      await updateStateToAbort([rider.id])
      rider.state = 0
    },
    async onOpen(rider) {
      await updateStateToNomral([rider.id])
      rider.state = 1
    },
    async onRest(rider) {
      await updateBusinessStateToRest([rider.id])
      rider.workState = 0
    },
    async onWork(rider) {
      await updateBusinessWorkState([rider.id])
      rider.workState = 1
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rider/rider/export', {
        ...this.queryParams
      }, `rider_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
